package com.ytf.dogbox.dogHttp;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.ytf.dogbox.bean.DownloadItem;
import com.ytf.dogbox.db.SqliteManager;
import com.ytf.dogbox.db.UploadItem;
import com.ytf.dogbox.util.Log;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;



/**
 * @author tiwolf_li
 * @Date on 2020/6/23
 * @Description
 */
public class ThreadPoollExcutorUtil implements IUploadFileStatusListener{

    //线程进度回调
    private final static int THREAD_PROGRESS_CODE=100;
    //线程完成
    private final static int THREAD_FINISH_CODE=101;
    //线程被中断
    private final static int THREAD_INTERRUPT_CODE=102;
    //所有线程完成
    private final static int THREAD_ALL_SUCCESS_CODE=103;
    //所有线程执行失败
    private final static int THREAD_ALL_FAILED_CODE=104;
    //下载成功
    private final static int DOWNLOAD_SUCCESS=105;
    //下载失败
    private final static int DOWNLOAD_FAIL=106;
    //全部下载任务完成
    private final static int THREAD_DOWNLOAD_ALL=107;
    //下载任务跑完
    private final static int DOWNLOAD_SUCCESS_FINISH=108;
    //app下载成功
    private final static int DOWNLOAD_PACKAGE_SUCCESS=109;
    //app下载失败
    private final static int DOWNLOAD_PACKAGE_FAIL=110;
    //app下载进度
    private final static int DOWNLOAD_PERSENT=111;
    //固件下载成功
    private final static int DOWNLOAD_BOARD_SUCCESS=112;
    //固件下载失败
    private final static int DOWNLOAD_BOARD_FAIL=113;
    //固件下载进度
    private final static int DOWNLOAD_BOARD_PERSENT=114;

    private final static int DOWNLOAD_ERROR=115;

    //上传警报文件成功
    private final static int POLICESUCCESS=116;
    //上传录制文件成功（普通）
    private final static int RECORDSUCCESS=117;
    //上传分片文件成功
    private final static int PARTSUCCESS=118;
    //上传中断
    private final static int UPLOADFAIL=119;
    //上传异常
    private final static int UPLOADERROR=120;
    //上传时的文件错误
    private final static int UPLOADFILEERROR=121;


    //handler传递进度值
    private final static String THREAD_FILEPATH="THREAD_FILEPATH";
    //handler传递md5值
    private final static String THREAD_MD5="THREAD_MD5";
    //handler传递position值
    private final static String THREAD_POSITION="THREAD_POSITION";
    //线程池核心数
    private int threadCore=3;
    //线程池
    private ExecutorService executor;
    //成功的数量
    int successCount=0;
    //失败的数量
    int failedCount=0;

    private OnUploadListener onUploadListener;
    private UploadHandler handler;

    static boolean isTrue=false;
    static String md5=null;

    static boolean uploadError=false;

    ArrayList<UploadItem> uploadArrayList;
    DownloadItem downloaditem;

    public ThreadPoollExcutorUtil(){
        init();
    }

    public ThreadPoollExcutorUtil(int threadCore){
        this.threadCore=threadCore;
        init();
    }

    public void setOnUploadListener(OnUploadListener uploadListener){
        this.onUploadListener=uploadListener;
    }

    private void init() {
        handler=new UploadHandler(this);
        successCount=0;
        failedCount=0;
        executor= Executors.newFixedThreadPool(threadCore);
    }

    public void shutDownNow(){
        //终端所有线程
        executor.shutdownNow();
    }



    /**
     * 这个是下载我司服务文件的方法
     * @param file
     * @param downloadItem
     * @param sqliteManager
     */
    public void downLoadFile(File file, DownloadItem downloadItem, SqliteManager sqliteManager){

        isTrue=false;
        uploadError=false;
        //历遍文件
        CountDownLatch countDownLatch=new CountDownLatch(1);
        downloaditem=downloadItem;

        executor.submit(new DownLoadFile(file,sqliteManager,countDownLatch,downloaditem,new OnThreadResultListener(){

            @Override
            public void onProgressChange(int persent) {

            }

            @Override
            public void onUpFinish() {
//                Log.e("tiwolf", "onFinish: 已完成" );
            }

            @Override
            public void onUpInterrupted() {
//                Log.e("tiwolf", "onInterrupted: 已停止 " );
            }

            @Override
            public void upFailed() {
//                Log.e("tiwolf", "failed: 已失败，记录下位置，下次断点下载" );
            }

            @Override
            public void onDownloadFinish() {
                handler.sendEmptyMessage(DOWNLOAD_SUCCESS);
            }

            @Override
            public void onDownloadInterrupted() {

            }

            @Override
            public void downloadFailed() {
                handler.sendEmptyMessage(DOWNLOAD_FAIL);
            }

            @Override
            public void downloadError(int flag) {
                Message msg=handler.obtainMessage();
                msg.what=DOWNLOAD_ERROR;
                msg.arg1=flag;
                handler.sendMessage(msg);
            }

            @Override
            public void downloadPackageSuccess() {

            }

            @Override
            public void downloadPackageFail() {

            }

            @Override
            public void onBoardProgressChange(int persent) {

            }

            @Override
            public void onBoardDownloadSuccess() {

            }

            @Override
            public void onBoardDownloadFail() {

            }
        }));

        downloadItem=null;

        //全部任务跑完,开始下一个
        handler.sendEmptyMessage(DOWNLOAD_SUCCESS_FINISH);
    }

    QiNiuDownLoadFile qiNiuDownLoadFile;
    public void stopDownload(boolean flag){
        if (qiNiuDownLoadFile!=null){
            qiNiuDownLoadFile.setStop(flag);
        }
    }

    /**
     * 这个是七牛云下载文件的方法
     * @param url
     * @param file
     * @param downloadItem
     * @param sqliteManager
     */
    public void qiniuDownloadFile(String url,File file, DownloadItem downloadItem, SqliteManager sqliteManager){

        isTrue=false;
        uploadError=false;
        //历遍文件
        CountDownLatch countDownLatch=new CountDownLatch(1);
        downloaditem=downloadItem;

        executor.submit(new QiNiuDownLoadFile(url,file,sqliteManager,countDownLatch,downloaditem,new OnThreadResultListener(){

            @Override
            public void onProgressChange(int persent) {

            }

            @Override
            public void onUpFinish() {
//                Log.e("tiwolf", "onFinish: 已完成" );
            }

            @Override
            public void onUpInterrupted() {
//                Log.e("tiwolf", "onInterrupted: 已停止 " );
            }

            @Override
            public void upFailed() {
//                Log.e("tiwolf", "failed: 已失败，记录下位置，下次断点下载" );
            }

            @Override
            public void onDownloadFinish() {
                handler.sendEmptyMessage(DOWNLOAD_SUCCESS);
            }

            @Override
            public void onDownloadInterrupted() {

            }

            @Override
            public void downloadFailed() {
                handler.sendEmptyMessage(DOWNLOAD_FAIL);
            }

            @Override
            public void downloadError(int flag) {
                Message msg=handler.obtainMessage();
                msg.what=DOWNLOAD_ERROR;
                msg.arg1=flag;
                handler.sendMessage(msg);
            }

            @Override
            public void downloadPackageSuccess() {

            }

            @Override
            public void downloadPackageFail() {

            }

            @Override
            public void onBoardProgressChange( int persent) {

            }

            @Override
            public void onBoardDownloadSuccess() {

            }

            @Override
            public void onBoardDownloadFail() {

            }
        }));

        downloadItem=null;

        //全部任务跑完,开始下一个
        handler.sendEmptyMessage(DOWNLOAD_SUCCESS_FINISH);
    }


    /**
     * 下载app方法
     * @param file
     * @param token
     * @param length
     * @param totalsize
     */
    public void downLoadPackageFile(File file, final String token,int length,String totalsize){

        //历遍文件
        CountDownLatch countDownLatch=new CountDownLatch(1);

        executor.submit(new DownLoadPostFile(file,token,length,totalsize,countDownLatch,new OnThreadResultListener(){

            @Override
            public void onProgressChange(int persent) {
                Log.e("tiwolf", "文件已经下载了："+persent );
                Message message=handler.obtainMessage();
                message.what=DOWNLOAD_PERSENT;
                message.arg1=persent;
                handler.handleMessage(message);
            }

            @Override
            public void onUpFinish() {

            }

            @Override
            public void onUpInterrupted() {

            }

            @Override
            public void upFailed() {
//                Log.e("tiwolf", "failed: 已失败，记录下位置，下次断点下载" );
            }

            @Override
            public void onDownloadFinish() {
//                handler.sendEmptyMessage(DOWNLOAD_SUCCESS);

            }

            @Override
            public void onDownloadInterrupted() {

            }

            @Override
            public void downloadFailed() {
//                handler.sendEmptyMessage(DOWNLOAD_FAIL);

            }

            @Override
            public void downloadError(int flag) {

            }

            @Override
            public void downloadPackageSuccess() {
                Log.e("tiwolf", "downloadPackageSuccess: 下载包裹成功" );
                handler.sendEmptyMessage(DOWNLOAD_PACKAGE_SUCCESS);
            }

            @Override
            public void downloadPackageFail() {
                Log.e("tiwolf", "downloadPackageSuccess: 下载包裹失败" );
                handler.sendEmptyMessage(DOWNLOAD_PACKAGE_FAIL);
            }

            @Override
            public void onBoardProgressChange(int persent) {

            }

            @Override
            public void onBoardDownloadSuccess() {

            }

            @Override
            public void onBoardDownloadFail() {

            }
        }));


        //全部任务跑完,开始下一个
        handler.sendEmptyMessage(DOWNLOAD_SUCCESS_FINISH);
    }

    /**
     * 下载固件方法
     * @param file
     * @param token
     * @param length
     * @param totalsize
     */
    public void downLoadBoardPackageFile(File file, final String token,int length,String totalsize){

        //历遍文件
        CountDownLatch countDownLatch=new CountDownLatch(1);

        executor.submit(new DownLoadBoardFile(file,token,length,totalsize,countDownLatch,new OnThreadResultListener(){

            @Override
            public void onProgressChange(int persent) {

            }

            @Override
            public void onUpFinish() {

            }

            @Override
            public void onUpInterrupted() {

            }

            @Override
            public void upFailed() {
//                Log.e("tiwolf", "failed: 已失败，记录下位置，下次断点下载" );
            }

            @Override
            public void onDownloadFinish() {
//                handler.sendEmptyMessage(DOWNLOAD_SUCCESS);

            }

            @Override
            public void onDownloadInterrupted() {

            }

            @Override
            public void downloadFailed() {
//                handler.sendEmptyMessage(DOWNLOAD_FAIL);

            }

            @Override
            public void downloadError(int flag) {

            }

            @Override
            public void downloadPackageSuccess() {

            }

            @Override
            public void downloadPackageFail() {

            }

            @Override
            public void onBoardProgressChange( int persent) {
                Log.e("tiwolf", "文件已经下载了："+persent );
                Message message=handler.obtainMessage();
                message.what=DOWNLOAD_BOARD_PERSENT;
                message.arg1=persent;
                handler.handleMessage(message);
            }

            @Override
            public void onBoardDownloadSuccess() {
                Log.e("tiwolf", "downloadPackageSuccess: 下载固件包裹成功" );
                handler.sendEmptyMessage(DOWNLOAD_BOARD_SUCCESS);
            }

            @Override
            public void onBoardDownloadFail() {
                Log.e("tiwolf", "downloadPackageSuccess: 下载固件包裹失败" );
                handler.sendEmptyMessage(DOWNLOAD_BOARD_FAIL);
            }
        }));


        //全部任务跑完,开始下一个
        handler.sendEmptyMessage(DOWNLOAD_SUCCESS_FINISH);
    }

    @Override
    public void onUploadsPolieceSuccess(UploadItem uploadItem) {
        try {
            if (uploadItem.getFilePath().contains("jpg")){
                File file=new File(uploadItem.getFilePath());
                file.delete();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Message message=handler.obtainMessage();
            message.obj=uploadItem;
            message.what=POLICESUCCESS;
            handler.sendMessage(message);
        }
    }

    @Override
    public void onUploadsRecordSuccess(UploadItem uploadItem) {
        try {
            if (uploadItem.getFilePath().contains("jpg")){
                File file=new File(uploadItem.getFilePath());
                file.delete();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Message message=handler.obtainMessage();
            message.obj=uploadItem;
            message.what=RECORDSUCCESS;
            handler.sendMessage(message);
        }
    }

    @Override
    public void onUploadPartSuccess(UploadItem uploadItem) {
        try {
            File file=new File(uploadItem.getFilePath());
            file.delete();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Message message=handler.obtainMessage();
            message.obj=uploadItem;
            message.what=PARTSUCCESS;
            handler.sendMessage(message);
        }
    }

    @Override
    public void onUpLoadInterrupted() {
        handler.sendEmptyMessage(UPLOADFAIL);
    }

    @Override
    public void onUploadError() {
        handler.sendEmptyMessage(UPLOADERROR);
    }

    @Override
    public void onFileError() {
        handler.sendEmptyMessage(UPLOADFILEERROR);
    }


    private static class UploadHandler extends Handler {

        private WeakReference<ThreadPoollExcutorUtil> weakReference;
        private UploadHandler(ThreadPoollExcutorUtil object){
            super(Looper.getMainLooper());//执行在UI线程
            weakReference=new WeakReference<>(object);
        }

        @Override
        public void handleMessage(Message msg) {
            ThreadPoollExcutorUtil threadPoollExcutorUtil=weakReference.get();
            if (threadPoollExcutorUtil!=null){
                String filePath=null;
                switch (msg.what){
                    case THREAD_PROGRESS_CODE:{
//                        filePath=data.getString(THREAD_FILEPATH);
                        break;
                    }
                    case THREAD_FINISH_CODE:{
                        Bundle data= (Bundle) msg.obj;
                        filePath=data.getString(THREAD_FILEPATH);
                        md5=data.getString(THREAD_MD5);
//                        Log.e("tiwolf", "handleMessage: "+filePath );
//                        Log.e("tiwolf", "handleMessage: "+md5 );
//                        Log.e("tiwolf", "handleMessage: "+filePath.split("\\.").length);
                        if (filePath!=null && filePath.split("\\.").length>1){
                            isTrue=true;
//                            Log.e("tiwolf", "handleMessage: 有单文件");
                        }
                        threadPoollExcutorUtil.onUploadListener.onThreadFinish(filePath);
                        break;
                    }
                    case THREAD_INTERRUPT_CODE:{
//                        threadPoollExcutorUtil.onUploadListener.onAllFailed();
                        break;
                    }
                    case THREAD_ALL_SUCCESS_CODE:{
//                        filePath=data.getString(THREAD_FILEPATH);
//                        md5=data.getString(THREAD_MD5);
//                        Log.e("tiwolf", "handleMessage: " );
                        if (isTrue || uploadError){
                            threadPoollExcutorUtil.onUploadListener.onAllSuccess(true,md5);
                        }else {
                            threadPoollExcutorUtil.onUploadListener.onAllSuccess(false,md5);
                        }

                        break;
                    }
                    case THREAD_ALL_FAILED_CODE:{
                        threadPoollExcutorUtil.onUploadListener.onAllFailed();
                        break;
                    }
                    case DOWNLOAD_FAIL:{
                        threadPoollExcutorUtil.onUploadListener.onDownloadFail();
                        break;
                    }
                    case DOWNLOAD_SUCCESS:{
                        threadPoollExcutorUtil.onUploadListener.onDownloadSuccess();
                        break;
                    }
                    case DOWNLOAD_SUCCESS_FINISH:{
                        threadPoollExcutorUtil.onUploadListener.onDownloadTreadSuccess();
                        break;
                    }

                    case DOWNLOAD_PACKAGE_SUCCESS:{
                        threadPoollExcutorUtil.onUploadListener.onDownloadPackageSuccess();
                        break;
                    }

                    case DOWNLOAD_PACKAGE_FAIL:{
                        threadPoollExcutorUtil.onUploadListener.onDownloadPackageFail();
                        break;
                    }
                    case DOWNLOAD_PERSENT:{
                        int persent=msg.arg1;
                        Log.e("tiwolf", "handleMessage: 得到的百分比为"+persent );
                        threadPoollExcutorUtil.onUploadListener.onThreadInterrupted(persent);
                        break;
                    }

                    case DOWNLOAD_BOARD_SUCCESS:{
                        threadPoollExcutorUtil.onUploadListener.onBoardDownloadSuccess();
                        break;
                    }

                    case DOWNLOAD_BOARD_FAIL:{
                        threadPoollExcutorUtil.onUploadListener.onBoardDownloadFail();
                        break;
                    }
                    case DOWNLOAD_BOARD_PERSENT:{
                        int persent=msg.arg1;
                        Log.e("tiwolf", "handleMessage: 得到的百分比为"+persent );
                        threadPoollExcutorUtil.onUploadListener.onBoardProgressChange(persent);
                        break;
                    }
                    case DOWNLOAD_ERROR:{
                        int errorCode=msg.arg1;
                        threadPoollExcutorUtil.onUploadListener.onDownloadError(errorCode);
                        break;
                    }
                    case POLICESUCCESS:{
                        UploadItem uploadItem= (UploadItem) msg.obj;
                        threadPoollExcutorUtil.onUploadListener.onUploadsPolieceSuccess(uploadItem);
                        break;
                    }
                    case RECORDSUCCESS:{
                        UploadItem uploadItem= (UploadItem) msg.obj;
                        threadPoollExcutorUtil.onUploadListener.onUploadsRecordSuccess(uploadItem);
                        break;
                    }
                    case PARTSUCCESS:{
                        UploadItem uploadItem= (UploadItem) msg.obj;
                        threadPoollExcutorUtil.onUploadListener.onUploadPartSuccess(uploadItem);
                        break;
                    }
                    case UPLOADFAIL:{
                        threadPoollExcutorUtil.onUploadListener.onUpLoadInterrupted();
                        break;
                    }
                    case UPLOADERROR:{
                        threadPoollExcutorUtil.onUploadListener.onUploadError();
                        break;
                    }
                    case UPLOADFILEERROR:{
                        threadPoollExcutorUtil.onUploadListener.onFileError();
                        break;
                    }
                }
            }

            super.handleMessage(msg);
        }
    }

    public ExecutorService getExecutor(){
        return executor;
    }


}
